package com.game;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;

public class GameThread extends Thread {
	private GameView view;
	private GamePlay gamePlay;
	private boolean isLoop = true;
	private Context context;

	GameThread(Context context, GameView view) {
		this.view = view;
		this.context = context;
	}

	@Override
	public void run() {
		// Initialize OpenGL...
		EGL10 egl = (EGL10) EGLContext.getEGL();
		EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);

		int[] version = new int[2];
		egl.eglInitialize(display, version);

		int[] configSpec = {EGL10.EGL_RED_SIZE, EGL10.EGL_DONT_CARE, 
				EGL10.EGL_GREEN_SIZE, EGL10.EGL_DONT_CARE,
				EGL10.EGL_BLUE_SIZE, EGL10.EGL_DONT_CARE, 
				EGL10.EGL_DEPTH_SIZE, 16,
				EGL10.EGL_NONE };

		EGLConfig[] configs = new EGLConfig[1];
		int[] numConfig = new int[1];
		egl.eglChooseConfig(display, configSpec, configs, 1, numConfig);
		EGLConfig config = configs[0];

		EGLContext glc = egl.eglCreateContext(display, config,
				EGL10.EGL_NO_CONTEXT, null);

		EGLSurface surface = egl.eglCreateWindowSurface(display, config,
				view.getHolder(), null);
		egl.eglMakeCurrent(display, surface, surface, glc);

		GL10 gl = (GL10) (glc.getGL());
		
		//initialize
		this.Init(gl);
		// GAME LOOP
		while (isLoop) {
			gamePlay.Render();
			egl.eglSwapBuffers(display, surface);
		}
		gamePlay.Exit();
		// Free OpenGL resources
		egl.eglMakeCurrent(display, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE,
				EGL10.EGL_NO_CONTEXT);
		egl.eglDestroySurface(display, surface);
		egl.eglDestroyContext(display, glc);
		egl.eglTerminate(display);
	}
	private void Init(GL10 gl){
		gamePlay = new GamePlay(context, gl, view.getWidth(), view.getHeight());
	}
	
	public void requestExitAndWait(){
		isLoop = false;
		try{
			join();
		}
		catch(InterruptedException ex){
			
		}
	}
}
